<!--自定义的规则输入框组件-->
<template>
  <div>
    <lay-row space="5">
      <lay-col>
        <div style="height: 2px"></div>
      </lay-col>
    </lay-row>
    <lay-row space="10" v-if="logicFlag">
      <lay-col md="22">
        <lay-button-group>
            <lay-button
              size="sm"
              class="btn1"
              v-for="item in operators"
              @click="addOperator(item)"
            >{{ item }}</lay-button>
        </lay-button-group>
      </lay-col>
    </lay-row>
    <lay-row space="10">
      <lay-field :size="size">
        <lay-col md="1">
          <lay-dropdown updateAtScroll ref="manualRef" :clickOutsideToClose="false">
              <lay-icon
                type="layui-icon-add-one"
                style="width: 20px;margin-right: 10px"
              ></lay-icon>
              <template #content>
                  <RulesTree
                    :mode="mode"
                    @insertRule="insertRule"
                    @cancelAction="cancelCheck"
                  ></RulesTree>
              </template>
          </lay-dropdown>
        </lay-col>
        <lay-col md="22">
            <a style="width: 10px;margin-top: 10px" v-for="(item, index) in tags" :key="item.no">
                <lay-dropdown updateAtScroll>
                    <span id="tagDemo" style="margin-left: 5px;">
                        <lay-input
                            v-if="item.edit"
                            ref="inputRef"
                            v-model="item.value"
                            autofocus
                            style="width:60px; height:24px"
                            @change="item.edit = !item.edit"
                        />
                      <lay-tag
                        v-else
                        closable
                        style="border: none;background-color: #fafafa;margin-bottom: 10px;color: #01aaed"
                        >
                        {{item.value}}
                        <template #close-icon style="width: 6px">
                          <lay-icon
                            type="layui-icon-close-fill"
                            style="color: #88abf3;position: relative;left: 5px; bottom: 8px;font-size: 14px;"
                            @click="deleteTag(item)"
                          ></lay-icon>
                        </template>
                      </lay-tag>
                    </span>
                    <template #content>
                        <lay-dropdown-menu>
                          <lay-dropdown-menu-item v-if="item.tag_type === 'const'" @click="item.edit=!item.edit">编辑</lay-dropdown-menu-item>
                          <lay-dropdown-menu-item @click="insertConst(index)">插入</lay-dropdown-menu-item>
                          <lay-dropdown-menu-item v-if="item.tag_type === 'rule'" @click="initCurrentParams(item)">设置</lay-dropdown-menu-item>
                        </lay-dropdown-menu>
                    </template>
                </lay-dropdown>
            </a>
            <lay-input
                v-model="newTag"
                placeholder="输入后回车"
                style="width: 80px;margin-left: 10px;margin-bottom: 8px;border: none"
                size="sm"
                @change="addTag(newTag)"
            ></lay-input>
        </lay-col>
        <lay-col md="1">
          <lay-icon size="sm" type="layui-icon-help-circle" @click="logicFlag = !logicFlag"></lay-icon>
        </lay-col>
      </lay-field>
    </lay-row>
    <lay-row space="10" v-if="paramsFlag">
      <lay-col md="22">
        <lay-row>
          <lay-col :md="paramWidth" v-for="item in currentNode.parameter">
            <lay-select
              v-if="item.select"
              size="sm"
              v-model="item.value_type"
              placeholder="请选择"
            >
              <template #prepend>值类型:</template>
              <lay-select-option :value="unit" :label="unit" v-for="unit in item.select"></lay-select-option>
            </lay-select>
            <lay-input
              v-else
              size="sm"
              v-model="item.value"
              :placeholder="item.description"
              style="width: 95%;"
            >
              <template #prepend>{{item.name}}:</template>
            </lay-input>
          </lay-col>
        </lay-row>
      </lay-col>
      <lay-col md="2">
        <lay-icon type="layui-icon-ok" @click="setParameter"></lay-icon>
        <lay-icon type="layui-icon-close" @click="paramsFlag=false"></lay-icon>
      </lay-col>
    </lay-row>
  </div>
</template>


<script lang="ts">
import RulesTree from "./RulesTree.vue";

export default {
    name: "TagInput",
    components: {
        RulesTree
    }
}
</script>

<script lang="ts" setup>
import {onMounted, ref, watch} from "vue";
// 引入 nanoid
import { nanoid } from 'nanoid';
import {queryTreeRulesApi} from "../../api/module/rule";
import {layer} from "@layui/layui-vue";



const {max, rawTags, mode, id, title, size, paramWidth, outParamsFlag} = defineProps({
    max: {type: Number, default: 20},
    rawTags: {type: Array, default: ref([])},
    mode: {type: String, default: 'scene'},
    id: {type: String, default: ''},
    title: {type: String, default: ''},
    size: {type: String, default: 'sm'},
    paramWidth: {type: Number, default: 8},
    outParamsFlag: {type: Boolean, default: false}
});

const newTag = ref('');  // 新标签
const tags = ref([]);    // 标签列表
const rules = ref([]);   // 规则树
const logicFlag = ref(false);
const paramsFlag = ref(false);
const currentNode: any = ref({});
const manualRef = ref();  // 下拉菜单回调函数

const emit = defineEmits(['setValue']);

onMounted(()=>{
    if(rawTags?.length>0){
        tags.value = rawTags;

        // 如果是‘规则参数固化’类型，则默认把固化的参数展示出来
        if(outParamsFlag === true) {
          initCurrentParams(tags.value[0])
        }
    }
});


// 监听tags，变化后提交给父组件
watch(tags, (newValue, oldValue)=>{
  console.log("值发生了变化：", newValue, oldValue)
  if(id === ''){
    emit('setValue', newValue)
  }else {
    emit('setValue', id, newValue)
  }
}, {deep: true});


const operators = ref(['+', '-', '*', '/', 'max', 'sum', 'avg', '(', ')', 'and', 'or']);

const addOperator = (key: String) =>{
    if(tags.value.length>=max){
        layer.msg('最多只能添加' + max.toString() + "个！")
    }else {
        if(key === 'max' || key === 'sum' || key === 'avg'){
            tags.value.push({no: nanoid(), value: key+'(', tag_type: 'const', edit: false, add: false});
            tags.value.push({no: nanoid(), value: ')', tag_type: 'const', edit: false, add: false});
        }else {
            const taskId = nanoid();
            tags.value.push({no: taskId, value: key, tag_type: 'const', edit: false, add: false});
        }
    }
};

const cancelCheck = () => {
  manualRef.value.hide();
}

const addTag = (val: any) => {
    if(tags.value.length>=max){
        layer.msg('最多只能添加' + max.toString() + "个！")
    }else {
        const taskId = nanoid();
        tags.value.push({no: taskId, value: val, tag_type: 'const', edit: false, add: false});
        newTag.value = '';
    }
};

const deleteTag = (node: any) => {
    console.log('deleteTag:')
    const index = tags.value.indexOf(node);
    console.log(index);
    tags.value.splice(index, 1);
    console.log(tags.value);
};

const insertConst = (index: number) => {
    console.log("insertConst:")
    console.log(index)
    if(tags.value.length>=max){
        layer.msg('最多只能添加' + max.toString() + "个！")
    }else {
        const taskId = nanoid();
        const newValue = {no: taskId, value: '', tag_type: 'const', edit: true, add: false};
        console.log(newValue)
        tags.value.splice(index + 1, 0, newValue);
        console.log(tags)
    }
};

//
const addNodeParams = (node: any) => {
    if(node.object === 'field'){
        node.value = "$d{" + node.database + '.' + node.table + '.' + node.field + "}";
        node.tag_type = 'field';
    }else {
        node.value = "${" + node.function_name + "}";
        node.tag_type = 'rule';
    }
    node.no = nanoid();
    node.edit = false;
    node.add = false;
    return node;
};


// 插入规则
const insertRule = (index: number, node: any) => {
  console.log("insertRule:", index, node)
  if(tags.value.length>=max){
    layer.msg('最多只能添加' + max.toString() + "个！")
  }else {
      let new_node = addNodeParams(node);
      const tagsLength = tags.value.length;
      if (index < tagsLength) {
          tags.value.splice(index, 0, new_node);
      } else {
          tags.value.push(new_node);
      }
  }
};

const initCurrentParams = (node: Object) => {
  currentNode.value = node;
  paramsFlag.value = true;
};

const setParameter = () => {
  console.log('currentNode:', currentNode.value)
  tags.value.forEach((unit: any) => {
    console.log('before', unit)
    if(unit.function_id === currentNode.value.function_id){
      unit.parameter = currentNode.value.parameter;
      console.log('after', unit)
    }
  })
  paramsFlag.value = false;
};

</script>

<style scoped>
/*.layui-icon .layui-icon-close-fill{*/
/*    position: absolute;*/
/*    font-size: 10px;*/
/*    margin-bottom: 20px;*/
/*    color: #01aaed;*/
/*}*/
</style>